package com.project.web.admin.controller.core;

import com.github.pagehelper.PageInfo;
import com.project.model.core.Admin;
import com.project.model.core.Role;
import com.project.web.admin.controller.common.BaseController;
import com.project.web.admin.service.core.AdminService;
import com.project.web.admin.service.core.RoleService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.yun.common.utils.appInterface.Message;

import javax.annotation.Resource;
import java.util.*;

@Controller("adminAdminController")
@RequestMapping("/admin/admin")
public class AdminController extends BaseController {

    private static final long serialVersionUID = 808225740258758386L;

    @Resource(name = "adminServiceImpl")
    public AdminService adminService;

    @Resource(name = "roleServiceImpl")
    public RoleService roleService;

    /**
     * 列表
     *
     * @param pageInfo
     * @param admin
     * @param model
     * @return String
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(PageInfo<Admin> pageInfo, Admin admin, Model model) {
        List<Admin> admins = adminService.selectList(admin);
        int size = admins.size();
        System.out.println(size);
        PageInfo<Admin> adminPageInfo = adminService.selectList(admin, pageInfo);
        model.addAttribute("page", adminPageInfo);

        Subject subject = SecurityUtils.getSubject();
        log.info("info");
        log.error("error");
        log.debug("debug");
        return "/admin/core/admin/list.ftl";
    }

    /**
     * 添加
     *
     * @param model
     * @return String
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("roles", roleService.selectList(new Role()));
        return "/admin/core/admin/add.ftl";
    }

    /**
     * 保存
     *
     * @param admin
     * @param redirectAttributes
     * @param roleIds
     * @return String
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Admin admin, RedirectAttributes redirectAttributes, Long[] roleIds) {

        //md5加密
        admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
        admin.setIsLocked(false);
        admin.setLockedDate(new Date());
        admin.setLoginFailCount(0);

        //保存admin、adminRole级联关系
        adminService.saveAdminCascadeRole(admin, roleIds);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 编辑
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, Model model) {
        Admin adminTemp = new Admin();
        adminTemp.setId(id);
        List<Admin> list = adminService.getAdminCascadeRole(adminTemp);
        Admin admin = list.get(0);
        List<Role> roleChildren = admin.getRoles();
        model.addAttribute("children", roleChildren);
        model.addAttribute("admin", admin);
        model.addAttribute("roles", roleService.selectList(new Role()));
        return "/admin/core/admin/edit.ftl";

    }

    /**
     * 更新
     *
     * @param admin
     * @param redirectAttributes
     * @param roleIds
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Admin admin, RedirectAttributes redirectAttributes, Long[] roleIds) {
        Admin adminTemp = new Admin();
        adminTemp.setId(admin.getId());
        List<Admin> list = adminService.getAdminCascadeRole(adminTemp);
        List<Long> delIds = new ArrayList<Long>();
        for (Role role : list.get(0).getRoles()) {
            if ("ROLE_ADMIN".equals(role.getRoleCode())) {
                addFlashMessage(redirectAttributes, Message.error("不能修改管理员用户"));
                return "redirect:list.jhtml";
            }
            delIds.add(role.getId());
        }

        //密码为空时忽略密码,不为空重新加密更新密码
        if (admin.getPassword() != null) {
            //md5加密
            admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
        }
        adminService.updateAdminCascadeRoles(admin, delIds, roleIds);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(Long id, RedirectAttributes redirectAttributes) {
        Admin admin = new Admin();
        admin.setId(id);
        List<Admin> list = adminService.getAdminCascadeRole(admin);
        for (Role role : list.get(0).getRoles()) {
            if ("ROLE_ADMIN".equals(role.getRoleCode())) {
                addFlashMessage(redirectAttributes, Message.error("不能删除管理员用户"));
                return "redirect:list.jhtml";
            }
        }
        admin.setFlag(false);
        admin.setStatus(1);
        adminService.update(admin);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 登陆手机号是否重复验证
     */
    @RequestMapping(value = "/checkMobile", method = RequestMethod.GET)
    @ResponseBody
    public boolean checkMobile(String mobile, Long id) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        Admin admin = new Admin();
        admin.setMobile(mobile);
        admin.setId(id);
        return adminService.getCountForOnly(admin);
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/editPassword", method = RequestMethod.GET)
    public String editPassword(Model model) {
        Admin admin = getCurrentAdmin();
        if (admin != null) {
            model.addAttribute("admin", admin);
        }
        return "/admin/core/admin/editPassword.ftl";
    }

    /**
     * 修改成功
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public String updatePassword(Model model, RedirectAttributes redirectAttributes, String passwordOne, String passwordFirst) {
        Admin admin = getCurrentAdmin();
        if (!DigestUtils.md5Hex(passwordFirst).equals(admin.getPassword())) {
            addFlashMessage(redirectAttributes, Message.error("当前密码错误"));
            return "redirect:/admin/admin/editPassword.jhtml";
        }
        if (admin != null) {
            admin.setPassword(DigestUtils.md5Hex(passwordOne));
            admin.getUserName();
            adminService.update(admin);
            addLayerFlashMessage(model, false, SUCCESS_MESSAGE);
        } else {
            addLayerFlashMessage(model, false, Message.error("操作失败"));
        }
        return LAYER_FORWARD_VIEW;
    }

    /**
     * 重置密码
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/rePassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> rePassword(Long id) {
        Admin admin = new Admin();
        admin.setId(id);
        //重置密码为admin123
        admin.setPassword(DigestUtils.md5Hex("admin123"));
        adminService.update(admin);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        return map;
    }

    /**
     * 简单更新
     *
     * @param admin
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/easyUpdate", method = RequestMethod.GET)
    public String update(Admin admin, RedirectAttributes redirectAttributes) {
        adminService.update(admin);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }
}
